package com.samnative.pineapple.main;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.samnative.pineapple.utils.GlideRequestOptions;
import com.samnative.pineapple.value.Config;
import com.samnative.pineapple.widget.IndicatorView;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;

import com.samnative.pineapple.widget.HackyViewPager;

import java.io.File;

import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher.OnViewTapListener;

/**
 * PhotoView 配合ViewPager显示大图浏览
 */
public class PhotoPagerActivity extends Activity {

    private static final String ISLOCKED_ARG = "isLocked";
    private ViewPager mViewPager;
    private IndicatorView v_indicator;
    /**
     * 点击的位置
     */
    private int position;

    /**
     * 图片地址,json数组
     */
    private String images;
    /**
     * 背景图
     */
    private ImageView iv_bg;

    private Context mContext;

    private boolean isDisImg;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pager_photoview);
        mContext = this;
        images = getIntent().getStringExtra("images");
        position = getIntent().getIntExtra("position", 0);
        isDisImg = getIntent().getBooleanExtra("isDisImg", false);
        iv_bg = (ImageView) findViewById(R.id.iv_bg);
        v_indicator = (IndicatorView) findViewById(R.id.v_indicator);
        mViewPager = (HackyViewPager) findViewById(R.id.view_pager);
        mViewPager.setAdapter(new SamplePagerAdapter());
        mViewPager.setOnPageChangeListener(mPCHListener);
        if (savedInstanceState != null) {
            boolean isLocked = savedInstanceState.getBoolean(ISLOCKED_ARG,
                    false);
            ((HackyViewPager) mViewPager).setLocked(isLocked);
        }
        mViewPager.setCurrentItem(position, false);

    }

    /**
     * @author WangPeng
     */
    private class SamplePagerAdapter extends PagerAdapter {

        private JSONArray jsonImg;

        public SamplePagerAdapter() {
            try {
                jsonImg = new JSONArray(images);
            } catch (JSONException e) {
                e.printStackTrace();
                jsonImg = new JSONArray();
            }
            v_indicator.setCount(jsonImg.length());
        }

        @Override
        public int getCount() {
            return jsonImg.length();
        }

        @Override
        public View instantiateItem(ViewGroup container, int position) {
            PhotoView photoView = new PhotoView(container.getContext());
            if (!isDisImg) {
                //网络图片
                Glide.with(mContext)
                        .load(Config._API_URL + jsonImg.optString(position))//图片地址
                        .apply(GlideRequestOptions.OPTIONS_400_400)
                        .into(photoView);

            } else {
                //本地图片
                File imgFile = new File(jsonImg.optString(position));
                Glide.with(mContext)
                        .load(imgFile)//图片地址
                        .apply(GlideRequestOptions.OPTIONS_400_400)
                        .into(photoView);
            }
            photoView.setOnViewTapListener(new OnViewTapListener() {

                @Override
                public void onViewTap(View view, float x, float y) {
                    // TODO Auto-generated method stub
                    finish();
                    overridePendingTransition(R.anim.activity_alpha_in,
                            R.anim.activity_alpha_out);
                }
            });

            // Now just add PhotoView to ViewPager and return it
            container.addView(photoView, LayoutParams.MATCH_PARENT,
                    LayoutParams.MATCH_PARENT);

            return photoView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

    }

    // @Override
    // public boolean onCreateOptionsMenu(Menu menu) {
    // getMenuInflater().inflate(R.menu.viewpager_menu, menu);
    // return super.onCreateOptionsMenu(menu);
    // }
    //
    // @Override
    // public boolean onPrepareOptionsMenu(Menu menu) {
    // menuLockItem = menu.findItem(R.id.menu_lock);
    // toggleLockBtnTitle();
    // menuLockItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
    // @Override
    // public boolean onMenuItemClick(MenuItem item) {
    // toggleViewPagerScrolling();
    // toggleLockBtnTitle();
    // return true;
    // }
    // });
    //
    // return super.onPrepareOptionsMenu(menu);
    // }
    // private void toggleViewPagerScrolling() {
    // if (isViewPagerActive()) {
    // ((HackyViewPager) mViewPager).toggleLock();
    // }
    // }
    // private void toggleLockBtnTitle() {
    // boolean isLocked = false;
    // if (isViewPagerActive()) {
    // isLocked = ((HackyViewPager) mViewPager).isLocked();
    // }
    // String title = (isLocked) ? getString(R.string.menu_unlock)
    // : getString(R.string.menu_lock);
    // if (menuLockItem != null) {
    // menuLockItem.setTitle(title);
    // }
    // }

    private boolean isViewPagerActive() {
        return (mViewPager != null && mViewPager instanceof HackyViewPager);
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        if (isViewPagerActive()) {
            outState.putBoolean(ISLOCKED_ARG,
                    ((HackyViewPager) mViewPager).isLocked());
        }
        super.onSaveInstanceState(outState);
    }

    private OnPageChangeListener mPCHListener = new OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            v_indicator.scrollTo(position);
        }

        @Override
        public void onPageScrolled(int position, float positionOffset,
                                   int positionOffsetPixels) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("大图浏览");
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("大图浏览");
        MobclickAgent.onResume(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            overridePendingTransition(R.anim.activity_alpha_in,
                    R.anim.activity_alpha_out);
        }

        return super.onKeyDown(keyCode, event);
    }

}
